package com.pj.common.base

import androidx.lifecycle.*
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.pj.common.exception.HttpExceptionHander
import com.pj.common.exception.HttpResponseException
import com.pj.common.extension.MsgEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


open class BaseViewModel : AndroidViewModel(Utils.getApp()), LifecycleObserver {
    val uiLoading = MutableLiveData<Boolean>()
    val uiEmpty = MutableLiveData<String>()
    val errorDialog = MutableLiveData<String>()
    val msgEvent = MutableLiveData<MsgEvent>()

    //刷新列表注册以下事件
    //空页面、错误页面
//    val noData = MutableLiveData<Boolean>()

    //是否还有更多
    val hasMore = MutableLiveData<Boolean>()

    /**
     * 协程
     * @param block 请求体
     * @param error 失败回调
     * @param complete  完成回调（无论成功失败都会调用）
     */
    fun launch(
        block: suspend CoroutineScope.() -> Unit,
        error: suspend CoroutineScope.(Exception) -> Unit = {},
        complete: suspend CoroutineScope.() -> Unit = {},
    ) {
        viewModelScope.launch {
            try {
                withContext(Dispatchers.IO) { block() }
            } catch (e: Exception) {
                e.printStackTrace()
                LogUtils.e("异常信息：${e.message}")
                error(e)
            } finally {
                complete()
            }
        }
    }

    /**
     * 网络请求
     * @param block 请求体
     * @param error 失败回调
     * @param complete  完成回调（无论成功失败都会调用）
     * @param isShowDialog 是否显示加载框,默认true
     * @param isShowToast 是否显示加载框,默认true
     * @param isShowEmptyView 状态布局
     */
    fun launch(
        block: suspend CoroutineScope.() -> Unit,
        error: suspend CoroutineScope.(HttpResponseException) -> Unit = {},
        complete: suspend CoroutineScope.() -> Unit = {},
        isShowLooading: Boolean = true,
        isShowDialog: Boolean = true,
        isShowEmptyView: Boolean = false
    ) {
        if (isShowLooading) uiLoading.postValue(true)
        launch(block, { e ->
            val throwable = if (e is HttpResponseException) {
                e
            } else {
                HttpExceptionHander.handleException(e)
            }
            LogUtils.e("异常信息：${throwable.message}")
            if (isShowEmptyView) uiEmpty.postValue(throwable.message)
            if (isShowDialog) errorDialog.postValue(throwable.message)
            error(throwable)
        }, {
            if (isShowLooading) uiLoading.postValue(false)
            complete()
        })
    }


    fun hasMoreData(flag: Boolean) {
        hasMore.postValue(flag)
    }

    fun showEmptyView(info:String){
        uiEmpty.postValue(info)
    }

    fun hideEmptyView(){
        uiEmpty.postValue("")
    }
}
